package handles

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
	"work-bench/cache"
	"work-bench/models"
)

func Add(c *gin.Context) {
	title := c.PostForm("title")
	content := c.PostForm("content")
	author := c.PostForm("author")

	if title == "" || content == "" || author == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "数据不能为空",
		})
		return
	}

	data := models.Video{

		Title:   title,
		Content: content,
		Author:  author,
	}

	err := models.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "发布失败",
		})
		return
	}

	redis_key := "video" + strconv.Itoa(int(data.ID))
	models.DB.Where("id=?", data.ID).Create(&data)
	jsonData, _ := json.Marshal(data)
	cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "发布成功",
	})
	return
}
func Del(c *gin.Context) {
	id := c.PostForm("id")

	var video models.Video

	err := models.DB.Where("id=?", id).Delete(&video).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "删除失败",
		})
		return
	}
	Redis_key := "video" + id
	cache.Rdb.Del(cache.Ctx, Redis_key)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "删除成功",
	})
	return
}

func List(c *gin.Context) {

	var video []models.Video

	err := models.DB.Find(&video).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询失败",
		})
		return
	}
	redis_key := "video_list"
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Find(&video)
		jsonData, _ := json.Marshal(video)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	}
	c.JSON(200, gin.H{
		"code": 500,
		"msg":  "查询成功",
		"data": video,
	})
	return

}
